import { ref } from 'vue'

export function useFileUpload(props: any, emit: any) {
  const fileInput = ref<HTMLInputElement>()
  const isDragOver = ref(false)

  const selectFile = () => {
    fileInput.value?.click()
  }

  const handleFileChange = (e: Event) => {
    const target = e.target as HTMLInputElement
    if (target.files && target.files.length > 0) {
      const file = target.files[0]
      if (validateFile(file)) {
        emit('update:modelValue', file)
      }
    }
  }

  const handleDragOver = () => {
    isDragOver.value = true
  }

  const handleDragLeave = () => {
    isDragOver.value = false
  }

  const handleDrop = (e: DragEvent) => {
    isDragOver.value = false
    if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
      const file = e.dataTransfer.files[0]
      if (validateFile(file)) {
        emit('update:modelValue', file)
      }
    }
  }

  const validateFile = (file: File): boolean => {
    const maxSizeBytes = props.maxSize * 1024 * 1024
    if (file.size > maxSizeBytes) {
      alert(`文件大小不能超过${props.maxSize}MB`)
      return false
    }
    return true
  }

  return {
    fileInput,
    isDragOver,
    selectFile,
    handleFileChange,
    handleDragOver,
    handleDragLeave,
    handleDrop
  }
}